<template>
  <PCard class="page-item-query-card-con" :isCardBorder="false" :shadow="'never'" :isHeadBottomBorder="true"
    :bodyStyle="{ width: '100%' }" v-bind="$attrs">
    <div v-if="headerConfig_.show" slot="header" class="card-title">
      <h3><span class="icon"></span>{{headerConfig_.title}}</h3>
      <div style="float: right;">
        <a-button @click="btnEvent(item)" :key="'btn-q-'+index" v-bind="item.itemAttr" v-for="(item,index) in headerConfig_.btnList">{{item.label}} </a-button>
      </div>
    </div>
    <div class="page-item-query-card-body">
      <div class="query">
        <QueryCard ref="QueryCard" :config="QueryConfig" :queryEvent="queryEvent"></QueryCard>
      </div>
      <div class="table">
        <a-tabs v-if="tabsConfig.dataList.length > 1" v-model="tabsConfig.activeKey" :default-active-key="tabsConfig.defaultActiveKey"
          @change="tabsChange">
          <a-tab-pane :key="index_" :tab="item.tabTitle" v-for="(item, index_) in tabsConfig.dataList">
            <a-table :ref="item.tableRef" bordered  :columns="item.columns" :dataSource="item.dataSource"
              :pagination="item.pagination" :loading="item.loading"
              :row-selection="rowSelectionList[index_] === true ? { selectedRowKeys: selectedRowKeys, onChange: onSelectChange,onSelect,onSelectAll,getCheckboxProps } : null"
              v-bind="item.otherAttrs"
              @change="(...args) => { handleTableChange(index_, ...args) }" :scroll="{ x: 800, y: 400 }">
              <!-- :row-selection="rowSelectionList[index_] === true ? { selectedRowKeys: selectedRowKeys, onChange: onSelectChange,onSelect,onSelectAll } : null" -->
              <!-- :row-selection="{onChange,onSelect,onSelectAll}" rowKey="key" -->
                <template v-for="(keyName) in customRenderList[index_]" :slot="keyName" slot-scope="text, record,index">
                  <!-- <slot :name="keyName" :data="{text, record,index,indent:{[keyName]:text}}"></slot> -->
                  <slot :name="keyName" :tabNum="index_" :text="text" :record="record" :index="index" :indent="{[keyName]:text}"></slot>
                </template>
                <!-- <template slot="money" slot-scope="text, record,index">
                  <slot name="money" :data="{text, record,index,indent:{money:text}}"></slot>
                </template> -->
            </a-table>
          </a-tab-pane>
        </a-tabs>
        <a-table  v-if="tabsConfig.dataList.length <= 1" :ref="tabsConfig.dataList.length>0 && tabsConfig.dataList[0].tableRef || ''"  rowKey="id"
          :columns="tabsConfig.dataList.length>0 && tabsConfig.dataList[0].columns || []" :dataSource="tabsConfig.dataList.length>0 && tabsConfig.dataList[0].dataSource || []"
          :pagination="tabsConfig.dataList.length>0 && tabsConfig.dataList[0].pagination" :loading="tabsConfig.dataList.length>0 && tabsConfig.dataList[0].loading"
          :row-selection="rowSelectionList[0] === true ? { selectedRowKeys: selectedRowKeys, onChange: onSelectChange,onSelect,onSelectAll,getCheckboxProps } : null"
          @change="(...args)=>{handleTableChange(0,...args)}" :scroll="{ x: 800, y: 500 }" v-bind="{bordered:true,...tabsConfig.dataList.length>0 && tabsConfig.dataList[0].otherAttrs}">
          <template v-for="(keyName) in customRenderList[0]" :slot="keyName" slot-scope="text, record,index">
                <slot :name="keyName" :data="{text, record,index,indent:{[keyName]:text}}"></slot>
              </template>
        </a-table>
      </div>
    </div>

  </PCard>
</template>

<script>
import UUID from '@/utils/uuid'
const timestamp = new Date().getTime();
const tableRef = UUID('MDUUID', 'page-item-query-card-con-table')
//#region
// const formItemAttr_ = { labelCol: { xxl: 5, xl: 12 }, wrapperCol: { xxl: 16, xl: 10 } }
// // { labelCol: { span: 5 }, wrapperCol: { span: 16 } }
// const formItemAttr1_ = { labelCol: { xxl: 5, xl: 8 }, wrapperCol: { xxl: 16, xl: 13 } }
// // { labelCol: { span: 6 }, wrapperCol: { span: 18 } }
// const formItemAttr2_ = { labelCol: { xxl: 6, xl: 10 }, wrapperCol: { xxl: 18, xl: 12 } }
// // labelCol: { span: 10 }, wrapperCol: { span: 14 }
// const formItemAttr3_ = { labelCol: { xxl: 10, xl: 9 }, wrapperCol: { xxl: 14, xl: 15 } }
// const formItemAttr4_ = { labelCol: { xxl: 10, xl: 6 }, wrapperCol: { xxl: 14, xl: 18 } }
// const columns = [
//   {
//     title: '名称',
//     dataIndex: 'name',
//     scopedSlots: { customRender: 'name' },
//   },
//   {
//     title: '金额',
//     className: 'column-money',
//     dataIndex: 'money',
//   },
//   {
//     title: '地址',
//     dataIndex: 'address',
//   },
// ];
// const columns1 = [
//   {
//     title: '名称1',
//     dataIndex: 'name',
//     scopedSlots: { customRender: 'name' },
//   },
//   {
//     title: '金额1',
//     className: 'column-money',
//     dataIndex: 'money',
//   },
//   {
//     title: '地址1',
//     dataIndex: 'address',
//   },
// ];

// const data = [
//   {
//     key: '1',
//     name: 'John Brown',
//     money: '￥300,000.00',
//     address: 'New York No. 1 Lake Park',
//   },
//   {
//     key: '2',
//     name: 'Jim Green',
//     money: '￥1,256,000.00',
//     address: 'London No. 1 Lake Park',
//   },
//   {
//     key: '3',
//     name: 'Joe Black',
//     money: '￥120,000.00',
//     address: 'Sidney No. 1 Lake Park',
//   },
//   {
//     key: '1',
//     name: 'John Brown',
//     money: '￥300,000.00',
//     address: 'New York No. 1 Lake Park',
//   },
//   {
//     key: '2',
//     name: 'Jim Green',
//     money: '￥1,256,000.00',
//     address: 'London No. 1 Lake Park',
//   },
//   {
//     key: '3',
//     name: 'Joe Black',
//     money: '￥120,000.00',
//     address: 'Sidney No. 1 Lake Park',
//   },
//   {
//     key: '1',
//     name: 'John Brown',
//     money: '￥300,000.00',
//     address: 'New York No. 1 Lake Park',
//   },
//   {
//     key: '2',
//     name: 'Jim Green',
//     money: '￥1,256,000.00',
//     address: 'London No. 1 Lake Park',
//   },
//   {
//     key: '3',
//     name: 'Joe Black',
//     money: '￥120,000.00',
//     address: 'Sidney No. 1 Lake Park',
//   },
//   {
//     key: '1',
//     name: 'John Brown',
//     money: '￥300,000.00',
//     address: 'New York No. 1 Lake Park',
//   },
//   {
//     key: '2',
//     name: 'Jim Green',
//     money: '￥1,256,000.00',
//     address: 'London No. 1 Lake Park',
//   },
//   {
//     key: '3',
//     name: 'Joe Black',
//     money: '￥120,000.00',
//     address: 'Sidney No. 1 Lake Park',
//   },
// ];

// console.log(timestamp);
//#endregion
export default {
  name: 'PageItemQueryCard',
  props: {
    // eventPool(index,type,data)
    // index 表示table的序号，从0开始
    // type 的值有 query  tabChange  tableChange  tableSelect  tableSelectAll  btnClick  query-*
    // 当type 是 query-* 的类型是表示是查询和重置之外的按钮事件， * 表示对应按钮的英文名称   此时对应的data为空
    // data 表示操作时的参数 包含：查询条件  对应的table的分页数据
    eventPool: { type: Function },
    // [{tabName:'',columns:[],dataSource:[],otherAttrs:{}, showRowSelection:true,isSingleChoice:false}]
    // tabName 表示 tab的名称，必填，当 tableList的长度为1时，此名称不显示，组件会自动切换成无tabs的模式
    // columns 对应的table的列名
    // dataSource 对应的table的数据
    // current: 1, 非必填
    // pageSize: 10, 非必填
    // total: 0, 用于控制分页，当值为0时，不显示分页  非必填
    // pageSizeOptions: ['10', '20', '30'], 非必填
    // showRowSelection 表示是否启用选择框
    // isSingleChoice 表示选择框是否为单选  默认为 true 表示单选  false 表示多选
    // otherAttrs 对应table的别的属性，即 a-table 组件的其他api属性
    // disabledList 用于控制那条数据禁止选择  如：[  { entId: 1210202 },{ entId: 1210216 }  ]
    tableList: { type: Array, default: () => [] },
    // 具体参数参照 QueryCard 组件的传参
    QueryCardConfig:{type:Object},
    // 头部表和相对应的按钮的设置 {show:true，title:'标题'，btnList：[{label:'按钮的名称', itemAttr:{ 按钮的其他属性 兼容 Ant Design 按钮的所有属性}}]}
    // show 表示是否要显示头部的标题和对应的按钮
    headerConfig:{type:Object}

  },
  data() {
    return {
      temptableRef:tableRef,
      expandedRowKeys:[],
      headerConfig_:{
        show:true,
        title:'这是标题',
        btnList:[
          // {label:'返 回', itemAttr:{type:'primary', icon:'left'}}
        ]
      },
      QueryConfig: {
        pageFormConfig:{
          defaultFormConfig:{
            columnCount:3,
            layout:'horizontal',
            labelCol:{span: 6},
            wrapperCol:{span: 18},
            rowAttr:{
              // type:'',
              // justify:'',
              // gutter:'',
              // align:'',
            },
            celAttr:{
              // flex:'',
              // offset:'',
              // order:'',
              // pull:'',
              // push:'',
              span:8,
              // xxl:{},
            }
          },
          formConfig:{
            columnCount:4,
            layout:'horizontal',
            labelCol:{span: 6},
            wrapperCol:{span: 18},
            rowAttr:{
              // type:'',
              // justify:'',
              // gutter:'',
              // align:'',
            },
            celAttr:{
              // flex:'',
              // offset:'',
              // order:'',
              // pull:'',
              // push:'',
              span:6,
              // xxl:{},
            }
          },
        },
        layoutConfig: {
          // 查询框的外部阴影  show-box-shadow
          boxShadow: false,
          // 是否显示默认条件下的下边框线  show-border-bottom
          defaultQueryBorderBottom: false,
        },
        btnGroupConfig: {
          btnList: [
            // { isDefault: true, label: '导出表单', eventKey: 'exportPage', isEvent: true, itemAttr: { icon: 'download' } },
          ],
        },
        formListConfig: {
          // 表示条件下拉的每行显示的条件个数
          columnCount: 4,
          // isDefault 表示要在默认位置显示的查询条件  suffix="RMB"
          formList: [
            // { isDefault: true, enName: 'entName', cnName: '企业名称', type: 'input', value: '', itemAttr: { placeholder: '请输入企业名称', allowClear: true }, formItemAttr: formItemAttr_ },
            // { isDefault: true, enName: 'legalName', cnName: '企业负责人', type: 'input', value: '', itemAttr: { placeholder: '请输入企业负责人', allowClear: true }, formItemAttr: formItemAttr_ },
            // {
            //   isDefault: true, enName: 'status', cnName: '企业状态', type: 'select', value: '',
            //   itemAttr: { placeholder: '请选择企业状态', allowClear: true },
            //   formItemAttr: formItemAttr_,
            //   optionList: []
            // },
            // // createTime  lastCreateTime
            // { enName: 'createTime', cnName: '注册时间', type: 'rangePicker', value: [], itemAttr: { valueFormat: 'YYYY-MM-DD', placeholder: ['开始日期', '结束日期'] }, formItemAttr: formItemAttr1_ },
            // // serviceEnd  lastServiceEnd
            // { enName: 'serviceEnd', cnName: '服务截止日期', type: 'rangePicker', value: [], itemAttr: { valueFormat: 'YYYY-MM-DD', placeholder: ['开始日期', '结束日期'] }, formItemAttr: formItemAttr2_ },
            // //  invoiceAmount  lastInvoiceAmount
            // { enName: 'invoiceAmount', cnName: '累计开票金额', type: 'inputRange', value: [], itemAttr: { suffix: '元' }, formItemAttr: formItemAttr3_,isRequire:[{ validator: (rule, value, callback)=>{pageEvent('handleRegMoneyCheck',null,rule, value, callback)} }] },
            // // serviceFeeRate   lastServiceFeeRate
            // { enName: 'serviceFeeRate', cnName: '费率', type: 'inputRange', value: [], itemAttr: { suffix: '%' }, formItemAttr: formItemAttr4_ ,isRequire:[{ validator: (rule, value, callback)=>{pageEvent('handleRegMoneyCheck',null,rule, value, callback)} }]},
          ]
        },
      },

      tabsConfig: {
        activeKey:0,
        defaultActiveKey: 0,
        dataList: [
          // {
          //   tabTitle: 'Tab 1',
          //   tableRef: tableRef,
          //   loading: false,
          //   columns: columns,
          //   dataSource: data,
          //   pagination: {
          //     current: 1,
          //     pageSize: 10,
          //     total: 0,
          //     pageSizeOptions: ['10', '20', '30'],
          //     showTotal: (total, range) => {
          //       return " 共" + total + "条"
          //     },
          //     showSizeChanger: true,
          //   }
          // },
          // {
          //   tabTitle: 'Tab 2',
          //   tableRef: tableRef,
          //   loading: false,
          //   columns: columns1,
          //   dataSource: data,
          //   pagination: {
          //     current: 1,
          //     pageSize: 10,
          //     total: 0,
          //     pageSizeOptions: ['10', '20', '30'],
          //     showTotal: (total, range) => {
          //       return " 共" + total + "条"
          //     },
          //     showSizeChanger: true,
          //   }
          // },
        ]
      },
      queryParam: {
        // 0: {
        //   data: {},
        //   pageNo: 1,
        //   pageSize: 10,
        // },
        // 1: {
        //   data: {},
        //   pageNo: 1,
        //   pageSize: 10,
        // },
      },
      customRenderList:{},
      selectedRowKeys: [],
      // 用于存储哪个表要显示 rowSelection
      rowSelectionList:{},
      // 用于存储 是否为单选
      singleChoiceList:{},
      // 用于存储当前table选中的数据
      tableSelectDataList:{},
      rowKeyNum:timestamp,
    }
  },
  watch: {
    headerConfig: {
      handler(val) {
        if (Object.prototype.toString.call(val) === '[object Object]') {
          this.headerConfig_ = val
        }
        // console.log('formConfig watch ==>',val);
      },
      deep: true,
      immediate: true
    },
    tableList: {
      handler(val) {
        if (Object.prototype.toString.call(val) === '[object Array]') {
          this.setTabsConfigData(val)
        }
        // console.log('数据表 tableList watch ==>',val);
      },
      deep: true,
      immediate: true
    },
    QueryCardConfig: {
      handler(val) {
        if (Object.prototype.toString.call(val) === '[object Object]') {
          const tempObj = JSON.parse(JSON.stringify(this.QueryConfig))
          this.QueryConfig = Object.assign({},tempObj,val)
        }
      },
      deep: true,
      immediate: true
    },
  },
  methods: {
    setTabsActiveNum(tabNum){
      this.tabsConfig.activeKey =tabNum
    },
    queryEvent(type, data) {
      // console.log('查询事件',type, data); // exportPage
      const activeKey = this.tabsConfig.activeKey
      if (type === 'query') {
        this.queryParam[activeKey].data = data
        this.eventPool && this.eventPool(activeKey, 'query', this.queryParam[activeKey])
      }
      if (type === 'clear') {
        this.queryParam[activeKey].data = data
        this.eventPool && this.eventPool(activeKey, 'clear', this.queryParam[activeKey])
      }
      if (type !== 'clear'&& type !== 'query') {
        this.eventPool && this.eventPool(activeKey, 'query-'+type)
      }
    },
    handleTableChange(index, pagination, filters, sorter) {
      this.$refs.QueryCard.getQueryData()
      this.$nextTick(() => {
        const activeKey = this.tabsConfig.defaultActiveKey
        const tempqueryParam = {data:{},pageNo:0,pageSize:10}
        tempqueryParam.data = this.$refs.QueryCard.formsDataList
        tempqueryParam.pageNo = pagination.current
        tempqueryParam.pageSize = pagination.pageSize
        this.queryParam[activeKey] = tempqueryParam
        // this.queryParam[activeKey].data = this.$refs.QueryCard.formsDataList
        // this.queryParam[index].pageNo = pagination.current
        // this.queryParam[index].pageSize = pagination.pageSize
        // //分页、排序、筛选变化时触发
        this.tabsConfig.dataList[index].pagination = pagination;
        // 还需要触发 查询表格数据的事件
        // console.log('查询表格数据的事件===>', activeKey, index, pagination,pagination.current,  tempqueryParam, tempqueryParam.pageNo);
        this.eventPool && this.eventPool(index, 'tableChange', tempqueryParam)
        // this.eventPool && this.eventPool(activeKey, 'tableChange', this.queryParam[activeKey])
      })
    },
    tabsChange(activeKey) {
      this.$refs.QueryCard.getQueryData()
      this.$nextTick(() => {
        this.tabsConfig.defaultActiveKey = activeKey
        this.queryParam[activeKey].data = this.$refs.QueryCard.formsDataList
        this.eventPool && this.eventPool(activeKey, 'tabChange', this.queryParam[activeKey])
      })
    },
    btnEvent(btnitem){
      this.eventPool && this.eventPool(this.tabsConfig.defaultActiveKey, 'btnClick', btnitem)
    },
    goBack() {
      this.$router.go(-1)
    },
    setTabsConfigData(dataList) {
      const tempObj = {
        tabTitle: '',
        tableRef: '',
        loading: false,
        columns: [],
        otherAttrs:{},
        dataSource: [],
        pagination: {
          current: 1,
          pageSize: 10,
          total: 0,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return " 共" + total + "条"
          },
          showSizeChanger: true,
        }
      }
      const tempRes = []
      dataList.forEach((item, index) => {
        // 、、 showRowSelection
        const { tabName, columns, dataSource, otherAttrs, showRowSelection=false, isSingleChoice=false,total,current,pageSize,pageSizeOptions } = item

        const initData = JSON.parse(JSON.stringify(tempObj))
        initData.tabTitle = tabName
        initData.columns = columns
        if(current){
          initData.pagination.current =current
        }
        if(total){
          initData.pagination.total =total
        }
        if(pageSize){
          initData.pagination.pageSize =pageSize
        }
        if(pageSizeOptions){
          initData.pagination.pageSizeOptions =pageSizeOptions
        }
        initData.dataSource = this.setDataSourceKey(dataSource)
        initData.tableRef = this.temptableRef + '' + (index + 100)
        initData.otherAttrs =otherAttrs
        this.getCustomRender(index,columns)
        this.rowSelectionList[index] = showRowSelection
        this.singleChoiceList[index] = isSingleChoice
        // 初始化 selectedRowKeys
        // this.selectedRowKeys[index] = []
        this.tableSelectDataList[index] = []
        tempRes.push(initData)
        this.queryParam[index] =  {
          data: {},
          pageNo: 1,
          pageSize: 10,
        }
      });
      this.tabsConfig.dataList = tempRes

    },
    setDataSourceKey(dataList=[]){
      let tempNum = this.rowKeyNum
      const tempResArr = []
      dataList.forEach(item=>{
        tempResArr.push({...item,key:tempNum})
        tempNum++
      })
      this.rowKeyNum = tempNum
      return tempResArr
    },
    getCustomRender(index,columns=[]){
      const tempArr = []
      columns.forEach(item=>{
        const {scopedSlots} = item
        if(scopedSlots && scopedSlots.customRender){
          tempArr.push(scopedSlots.customRender)
        }
      })
      this.customRenderList[index] = tempArr
    },
    onSelectChange(selectedRowKeys) {
      const tempKeyNum = this.tabsConfig.defaultActiveKey
      const isSingle = this.singleChoiceList[tempKeyNum]
      if(isSingle === true){

        const temppageSize = this.queryParam[tempKeyNum].pageSize
        if(temppageSize===selectedRowKeys.length){
          this.selectedRowKeys=[]
        }else{
          this.selectedRowKeys= [selectedRowKeys[selectedRowKeys.length-1]]
        }
      } else {
        this.selectedRowKeys= selectedRowKeys
      }
      // console.log('selectedRowKeys changed: ', selectedRowKeys,this.selectedRowKeys);

    },

    onSelect(record, selected, selectedRows, nativeEvent) {
      // console.log('223 单选=》',record, selected, selectedRows,nativeEvent);
      const tempKeyNum = this.tabsConfig.defaultActiveKey
      const isSingle = this.singleChoiceList[tempKeyNum]
      let tempArr = []
      if(isSingle === true){
        // const temppageSize = this.queryParam[tempKeyNum].pageSize
        // if(temppageSize===selectedRows.length){
        //   tempArr=[]
        // }else{
        //   tempArr= [selectedRows[selectedRows.length-1]]
        // }
        tempArr = selectedRows
      } else {
        tempArr =selectedRows
      }
      this.tableSelectDataList[tempKeyNum] = tempArr
      this.eventPool && this.eventPool(this.tabsConfig.defaultActiveKey, 'tableSelect', tempArr,this.selectedRowKeys)
    },
    onSelectAll (selected, selectedRows, changeRows) {
      // console.log('333 全选=》',selected, selectedRows, changeRows);
      const tempKeyNum = this.tabsConfig.defaultActiveKey
      const isSingle = this.singleChoiceList[tempKeyNum]
      let tempArr = []
      if(isSingle === true){
        tempArr= []
      } else {
        tempArr =selectedRows
      }
      this.tableSelectDataList[tempKeyNum] = tempArr
      this.eventPool && this.eventPool(this.tabsConfig.defaultActiveKey, 'tableSelectAll', tempArr,this.selectedRowKeys)
    },
    getCheckboxProps(record) {
      // console.log('getCheckboxProps====>',record);
      // entId:1210202  1210216   1210222
      const { disabledList } = this.tableList

      let disabledObjList = [
        // { entId: 1210202 },
        // { entId: 1210216 },
        // { entId: 1210222 },
      ]
      if (disabledList && disabledList.length > 0) {
        disabledObjList = disabledList
      }
      const temp = { props: {} }
      disabledObjList.forEach(item => {
        const disabledObjArr = Object.keys(item)
        const key = disabledObjArr[0]
        const val = item[key]
        if (record[key] == val) {
          temp['props'] = { disabled: record[key] == val, [key]: record[key] }
        }
      })
      return { ...temp }
      //  {
      //   props: {
      //     disabled: record.entId == '1210202', // Column configuration not to be checked
      //     name: record.entId ,
      //   },
      // }
    }
  }
}
</script>

<style lang="less">
.page-item-query-card-con {
  .card-title {
    //font-size: 28px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    display: flex;
    justify-content: space-between;
    //color: #333333;
    h3{
      font-size: 20px;
      font-weight: bold;
      //margin-bottom: 30px;
    }
  }

  .card-head{
    padding: 18px 20px 0 20px;
  }
  .card-body {
    padding: 15px 20px 20px 20px;
  }

  .page-item-query-card-body {
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-direction: column;
    padding-bottom: 30px;

    .query {
      width: 100%;
      // margin: 0 0 10px 0;
    }

    .table {
      // margin: 10px 0;
      width: 100%;

      .ant-table-thead>tr>th,
      .ant-table-tbody>tr>td {
        padding: 8px;
      }
    }
  }
}
</style>
